package com.learning.datastruct.heap;

import java.util.Comparator;

/**
 * @author ZLH
 */
@SuppressWarnings("unchecked")
public class MyBinaryHeap<E> extends MyAbstractHeap<E> implements MyHeap<E> {
    private E[] elements;
    private static final int DEFAULT_CAPACITY = 10;

    public MyBinaryHeap(E[] elements, Comparator<E> comparator)  {
        super(comparator);
        if (elements == null || elements.length == 0) {
            this.elements = (E[]) new Object[DEFAULT_CAPACITY];
        } else {
            size = elements.length;
            int capacity = Math.max(elements.length, DEFAULT_CAPACITY);
            this.elements = (E[]) new Object[capacity];
            // for (int i = 0; i < elements.length; i++) this.elements[i] = elements[i];
            System.arraycopy(elements, 0, this.elements, 0, elements.length);
            heapify();
        }
    }

    public MyBinaryHeap(E[] elements)  {
        this(elements, null);
    }

    public MyBinaryHeap(Comparator<E> comparator) {
        this(null, comparator);
    }

    public MyBinaryHeap() {
        this(null, null);
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[i] = null;
        }
        size = 0;
    }

    @Override
    public E get() {
        emptyCheck();
        return elements[0];
    }

    @Override
    public E remove() {
        emptyCheck();
        int lastIndex = --size;
        E root = elements[0];
        elements[0] = elements[lastIndex];
        elements[lastIndex] = null;
        siftDown(0);
        return root;
    }

    @Override
    public void add(E element) {
        ensureCapacity(size + 1);
        elements[size++] = element;
        siftUp(size - 1);
    }

    @Override
    public E replace(E element) {
        emptyCheck();
        E root = elements[0];
        elements[0] = element;
        siftDown(0);
        return root;
    }

    private void emptyCheck() {
        if (size == 0) {
            throw new IndexOutOfBoundsException("Heap is empty");
        }
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) {
            return;
        }
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        // for (int i = 0; i < size; i++) newElements[i] = elements[i];
        System.arraycopy(elements, 0, newElements, 0, size);
        elements = newElements;
    }

    /**
     * 将index位置元素上滤
     * @param index 要上滤的索引值
     */
    private void siftUp(int index){
        E element = elements[index];
        while (index > 0) {
            int parentIndex = (index - 1) >> 1;
            E parent = elements[parentIndex];
            if (compare(element, parent) <= 0) {
                break;
            }
            elements[index] = parent;
            index = parentIndex;
        }
        elements[index] = element;
    }

    /**
     * 将index位置元素下滤
     * @param index 要下滤的索引值
     */
    private void siftDown(int index) {
        E element = elements[index];
        int half = size >> 1;
        // index < 第一个叶子节点的索引 == 非叶子节点的数量
        while (index < half) {
            // index的节点有2种情况
            // 1.只有左子节点
            // 2.同时有左右子节点
            int childIndex = (index << 1) + 1;
            E child = elements[childIndex];
            // 右子节点
            int rightIndex = childIndex + 1;
            // 选出左右子节点最大的那个
            if (rightIndex < size && compare(elements[rightIndex], child) > 0) {
                child = elements[childIndex = rightIndex];
            }
            if (compare(element, child) >= 0) {
                break;
            }
            // 将子节点存放到index位置
            elements[index] = child;
            // 重新设置index
            index = childIndex;
        }
        elements[index] = element;
    }

    /**
     * 建堆
     */
    private void heapify(){
        // 自下而上的下滤
        for (int i = (size >> 1) - 1; i >= 0; i--) {
            siftDown(i);
        }
    }
}
